package com.mkirl;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.widget.EditText;

import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;

public class GamesItemizedOverlay extends ItemizedOverlay {

	private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
	Context mContext;

	public ArrayList<OverlayItem> getList() {
		return mOverlays;
	}
	
	public GamesItemizedOverlay(Drawable defaultMarker, Context context) {
		super(boundCenterBottom(defaultMarker));
		mContext = context;
	}
	
	@Override
	protected OverlayItem createItem(int i) {
	  return mOverlays.get(i);
	}

	@Override
	public int size() {
	  return mOverlays.size();
	}

	public void addOverlay(OverlayItem overlay) {
	    mOverlays.add(overlay);
	    populate();
	}
	
	public void removeOverlay(OverlayItem overlay) {
		mOverlays.remove(overlay);
	}
	@Override
	protected boolean onTap(int index) {
		OverlayItem item = mOverlays.get(index); //set item to the clicked overlay item
		
		//tenatively set player's gameID, which may be changed later before reaching server, or sent to server after joining.
	    ((MKIRL)mContext).thisPlayer.setGameID(item.getTitle());
		
	    //building the popup
	    AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
	    dialog.setTitle(item.getTitle());
	    dialog.setMessage("\nEnter Player Name:");

	    // Set an EditText view to get user input 
	    final EditText input = new EditText(mContext);
	    dialog.setView(input); //add the input EditText to the popup
	    
	    dialog.setPositiveButton("Join", new DialogInterface.OnClickListener() {
	    public void onClick(DialogInterface dialog, int whichButton) {
	    	String value = input.getEditableText().toString();
	    	if (!value.equals("")) {
		    	((MKIRL)mContext).thisPlayer.setPlayerID(value);
		    	((MKIRL)mContext).joinGame();
	    	}
	    	else {
	    		((MKIRL)mContext).tickerTextView.setText("You cannot enter an empty name");
	    	}
	      }
	    });
	    
	    dialog.setNegativeButton("Back", new DialogInterface.OnClickListener() {
	      public void onClick(DialogInterface dialog, int whichButton) {
	        // Canceled.
	      }
	    });
	    dialog.show();
	    return true;
	}
	

}
